<template>
	<view style="
    min-height: 800px;
">
		<scroll-view id="nav-bar" scroll-x class="nav  bg-black">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :id="'tab'+index" v-for="(item,index) in tabBars" :key="index" :class="index==tabCurrentIndex?'text-yellow cur':''"
				 @tap="changeTab(index)">
					{{item.name}}
				</view>
			</view>
		</scroll-view>
		<!-- 下拉刷新组件 -->
		<!-- <mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll"> -->
		<!-- 内容部分 -->
		<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
			<swiper-item v-for="(tabItem,index) in tabBars" :key="index">
				<scroll-view class="panel-scroll-box" scroll-y="true" @scrolltolower="loadMore">
					<!-- 委托列表 -->
					<view class="cu-list grid col-2 no-border " v-for="(item, index) in tabItem.newsList" :key="index">
						<view class="cu-item text-left">
							<view>
								<view class="text-lg row text-cyan">{{item.nickname}}</view>
								<view class="text-xs row"> </view>
							</view>
							<!-- <text class="text-xs nowrap">{{item.addtime_text}}</text> -->
						</view>
						<view class="cu-item text-right">
							<view>
								<!-- <text class="text-xs">94.88%</text> -->
							</view>

						</view>
						<view class="cu-item  text-left" style="width: 70%;">
							<view>
								<view class="text-df row">限额 {{item.min}}-{{item.max}}</view>
								<view class="text-df row text-gray margin-left-sm">CNY</view>
							</view>
							<view>
								<view class="text-df row">数量 {{(item.number-item.trade_number).toFixed(4)}}</view>
								<view class="text-df row text-gray margin-left-sm">USDT</view>
							</view>
							<view>
								<view class="row" v-if="item.is_wx">
									<image src="../static/wx.png" mode=""></image>
								</view>
								<view class="row" v-if="item.is_zfb">
									<image src="../static/zfb.png" mode=""></image>
								</view>
								<view class="row" v-if="item.is_yh">
									<image src="../static/yh.png" mode=""></image>
								</view>
							</view>

						</view>
						<view class="cu-item text-right" style="width: 30%;">
							<view>
								<view class="text-df row">{{item.price}}</view>
								<view class="text-df row text-gray">CNY</view>
							</view>

							<view style="line-height: 5;">
								<button class="cu-btn bg-gradual-purple" @tap="showModal('bottomModal',item)">{{item.type == '4' ? '出售':'购买'}}</button>
							</view>

						</view>

					</view>

					<!-- 上滑加载更多组件 -->
					<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
		<!-- </mix-pulldown-refresh> -->
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog">

				<view class="cu-list grid col-1 no-border " style="padding: 22px;">
					<view class="cu-item text-right">
						<view>
							<view class="row">
								<text @tap="hideModal">X</text>
							</view>

						</view>

					</view>
					<view class="cu-item text-left">
						<view>
							<view class="text-lg row ">向 {{this.pp.nickname}} {{this.pp.type == '4' ? '出售':'购买'}} USDT</view>
							<view class="text-xs row"> </view>
						</view>
						<!-- <text class="text-xs nowrap">{{item.addtime_text}}</text> -->
					</view>

					<view class="cu-item  text-left">
						<view>
							<view class="text-xsl row">{{this.pp.price}}</view>
							<view class="text-df row text-gray">CNY</view>
						</view>
						<view>
							<view class="text-df row">限额 {{this.pp.min}}-{{this.pp.max}}</view>
							<view class="text-df row text-gray">CNY</view>
						</view>
						<view>
							<view class="text-df row">数量 {{this.pp.number}}</view>
							<view class="text-df row text-gray">USDT</view>
						</view>


					</view>
					<view class="cu-item text-left">
						<view style="line-height: 6;">
							<view class="row">
								<image src="../static/wx.png" v-if="pp.is_wx"></image>
							</view>
							<view class="row">
								<image src="../static/zfb.png" v-if="pp.is_zfb"></image>
							</view>
							<view class="row">
								<image src="../static/yh.png" v-if="pp.is_yh"></image>
							</view>

						</view>
					</view>


				</view>

				<view class="cu-form-group">
					<view class="title">金额</view>
					<input type="number" placeholder="请输入金额" :value="total" v-on:input="fc1($event.target.value)"></input>
					<text> CNY</text>
				</view>
				<view class="cu-form-group">
					<view class="title">数量</view>
					<input type="number" placeholder="请输入数量" :value="number" v-on:input="fc2($event.target.value)"></input>
					<text>USDT</text>
				</view>
				<view class="cu-form-group">
					<button @tap="submit" class="cu-btn bg-yellow lg" style="width: -webkit-fill-available;margin: 39px 0px;">
						确认提交
					</button>
				</view>

				<!-- <view class="cu-list grid col-1 no-border tij">
					

					<view class="flex-sub  ">
						<view class="solid-bottom text-xs padding">
							温馨提示：提币前请再次确认您的地址
						</view>
					</view>
				</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex'
	// import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import json from '@/json'
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			// mixPulldownRefresh,
			mixLoadMore
		},
		props: {
			type: {
				type: String,
				default: () => {
					//4 买入 5 卖出
					return '4'
				}
			},
		},
		data() {
			return {
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				category_id: 0,
				TabCur: 0, //当前选项卡索引 
				modalName: null,
				pp: {},
				total: 0,
				price: 0,
				number: '',
			}
		},
		computed: {
			...mapState({
				userinfo: state => state.user.userinfo,
				myconfig: state => state.user.myconfig
			}),
			rule() {
				return this.myconfig.wall2cny;
			},
			tabList() {
				let arr = [];
				for (let key in this.rule) {
					arr.push({
						name: key,
						uri: 'trade2.entrust_buy',
						newsList: [],
						loadMoreStatus: 0, //加载更多 0加载前，1加载中，2没有更多了
						refreshing: 0,
						page: 1,
					})
				}
				return arr;
			},
			// number:{
			// 	get(){
			// 		if (this.total) {
			// 			return (this.total / this.price).toFixed(6);
			// 		} else {
			// 			return '';
			// 		}
			// 	},
			// 	set(v){
			// 		this.total=(v / this.price).toFixed(2)
			// 	}
			// }
			// total() {
			// 	if (this.number) {
			// 		return (this.number / this.price).toFixed(6);
			// 	} else {
			// 		return 10;
			// 	}
			// },
		},
		mounted() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		methods: {
			...mapActions(['getUserinfo']),
			//获取分类
			loadTabbars() {
				const arr = [];
				for (let key in this.rule) {
					arr.push({
						name: key,
						uri: 'trade2.entrust_buy',
						newsList: [],
						loadMoreStatus: 0, //加载更多 0加载前，1加载中，2没有更多了
						refreshing: 0,
						page: 1,
					})
				}
				this.tabBars = arr;
				this.loadNewsList('refresh');
			},
			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},
			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},
			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},
			//列表
			loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				console.log(type)
				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif

				if (type === 'refresh') {
					tabItem.page = 1;
				}
				// 请求数据
				let send = {
					ptype1: this.rule[tabItem.name],
					ptype2: '',
					type: this.type,
					page: tabItem.page
				};
				this.$http.post(tabItem.uri, send).then(res => {
					let list = res.data.data;
					if (type === 'refresh') {
						tabItem.newsList = []; //刷新前清空数组
						//下拉刷新 关闭刷新动画
						this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
						// #ifdef APP-PLUS
						tabItem.refreshing = false;
						// #endif
						tabItem.loadMoreStatus = 0;
					}
					list.forEach(item => {
						// item.id = parseInt(Math.random() * 10000);
						tabItem.newsList.push(item);
					})

					tabItem.loadMoreStatus = res.data.current_page >= res.data.last_page ? 2 : 0;
					tabItem.page += 1;
				})

			},
			cancle(id, type) {
				//撤单
				if (type == '4') {
					this.$http.post('cancle.buy', {
						id: id
					}).then(res => {
						console.log(res)
						if (res.msg) {
							this.$api.msg(res.msg)
						}
						this.loadNewsList('refresh');
						this.getUserinfo();
					})
				} else {
					this.$http.post('cancle.sale', {
						id: id
					}).then(res => {
						console.log(res)
						if (res.msg) {
							this.$api.msg(res.msg)
						}
						this.loadNewsList('refresh');
						this.getUserinfo();
					})
				}

			},
			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;

					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			showModal(name, item) {
				this.modalName = name;
				this.pp = item;
				this.total = '';
				this.number = '';
				this.price = this.pp.price;

			},
			hideModal() {
				this.modalName = null
			},
			submit() {
				// console.log('submit')
				// console.log(parseFloat(this.total) > 0)
				// console.log(parseFloat(this.number))
				if (parseFloat(this.total) > 0 == false) {
					this.hideModal();
					this.$api.msg('最低交易限额' + this.pp.min)
					return false;
				}
				if (parseFloat(this.number) > 0 == false) {
					this.hideModal();
					this.$api.msg('请输入交易数量')
					return false;
				}
				if (parseFloat(this.total) < parseFloat(this.pp.min)) {
					this.hideModal();
					this.$api.msg('最低交易限额' + this.pp.min)
					return false;
				}
				if (parseInt(this.number) > parseInt(this.pp.max)) {
					this.hideModal();
					this.$api.msg('最高交易限额' + this.pp.max)
					return false;
				}
				let send = {
					price: this.price,
					number: this.number,
					id: this.pp.id,
					ptype1: this.pp.ptype1,
					ptype2: this.pp.ptype1,
				}
				var trade2uri = 'trade2.clickbuy';
				if (this.type == '4') {
					//卖出
					trade2uri = 'trade2.clicksale';
				}
				this.$http.post(trade2uri, send).then(res => {
					console.log(res)

					if (res.msg) {
						this.hideModal();
						this.$api.msg(res.msg)
					}
					this.getUserinfo();
					if (res.code == 1) {
						if(this.type == '4'){
							//卖出
							uni.navigateTo({
								url: '/pages/user/order'
							}) 
						}else{
							//买入
							uni.navigateTo({
								url: '/pages/trade2/pay?data=' + JSON.stringify(res.data)
							})
						} 
					}
					// this.$refs.child.loadNewsList('refresh'); //刷新委托列表
				}).catch(err => {
					this.hideModal();
					this.$api.msg(err.msg)

				})

			},
			fc1(total) {
				// console.log(total)
				let vv = (total / this.price).toFixed(6);
				this.number = vv > 0 ? vv : '';
				this.total = total;
			},
			fc2(number) {
				// console.log(number)
				let vv = (number * this.price).toFixed(2);
				this.total = vv > 0 ? vv : '';
				this.number = number;
			},
			// tabSelect(e) {
			// 	this.tabCurrentIndex = e.currentTarget.dataset.id;
			// 	this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60
			// }
		}
	}
</script>

<style scoped>
	.cu-item .text-gray {
		width: 45px;
		display: inline-block;
	}

	.row {
		display: inline;
	}

	.bai {
		padding: 6px 12px;
		border-radius: 8px;
	}

	.nowrap {
		white-space: nowrap;
	}

	.cu-list {
		margin-top: 2px;
	}

	.cu-list.grid.no-border {
		padding: 3px 17px;
	}
	.nav .cu-item.cur {
	    border-bottom: 0px;
	}
	/* .nav .cu-item.cur {
		border-bottom: 1px solid;
	} */

	.swiper-box {
		min-height: 800px;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	image {
		width: 50rpx;
		height: 50rpx;
		margin-right: 9px;
	}

	.cu-dialog {
		background: #000000;
	}

	.input-placeholder {
		width: 110px;
	}

	.cu-form-group uni-input {
		text-align: left;
	}
</style>
